# -*- coding: utf-8 -*-
'''
  @author zhanghaisheng
  @date 2021/9/2
  @description get java code_coverage result
'''
from __future__ import division
import os
import requests
from xml.dom.minidom import parse, parseString
from ci_conclude.const import CODE
from ci_conclude.base import BaseConclude
from ci_conclude.qingstor import get_qingstor_path

class CoverageJavaConclude(BaseConclude):

    # 解析jacoco覆盖率统计报告，获取需要数据，jacoco_result_path为jacoco生成的jacoco.xml文件路径
    def get_java_coverage(self, jacoco_result_path):
        if jacoco_result_path.startswith("http"):
            res = requests.get(jacoco_result_path)
            if res.status_code == 200 and res.ok:
                domTree = parseString(res.text)
            else:
                return {}
        else:
            if os.path.exists(jacoco_result_path) is False:
                return 'jacoco.xml not exist!'
            domTree = parse(jacoco_result_path)
        if domTree is None:
            return 'no data!'
        else:
            rootNode = domTree.documentElement  # 获取jacoco.xml文档根元素
            covered_lines = covered_methods = covered_classes = missed_lines = missed_methods = missed_classes = coverage_line = coverage_method = coverage_class = ''
            packages = rootNode.getElementsByTagName("package")  # 获取元素内特定标签元素
            counters = rootNode.getElementsByTagName("counter")  # 获取元素内特定标签元素
            if counters is None:
                return 'result is null!'
            for counter in counters:
                type = counter.getAttribute("type") # 获取标签属性
                if type == 'LINE':
                    covered_lines = counter.getAttribute("covered")  # 获取标签属性
                    missed_lines = counter.getAttribute("missed") # 获取标签属性
                    coverage_line = round(int(covered_lines) / (int(covered_lines) + int(missed_lines)), 2)
                elif type == 'METHOD':
                    covered_methods = counter.getAttribute("covered")
                    missed_methods = counter.getAttribute("missed")
                    coverage_method = round(int(covered_methods) / (int(covered_methods) + int(missed_methods)), 2)
                elif type == 'CLASS':
                    covered_classes = counter.getAttribute("covered")
                    missed_classes = counter.getAttribute("missed")
                    coverage_class = round(int(covered_classes) / (int(covered_classes) + int(missed_classes)), 2)
            print(covered_lines)
            print(missed_lines)
            print(coverage_line)
            print(covered_methods)
            print(missed_methods)
            print(coverage_method)
            print(covered_classes)
            print(missed_classes)
            print(coverage_class)
            print(len(packages))
        data = {
            "line_nums": int(covered_lines) + int(missed_lines),  # 总行数
            "line_coverage": coverage_line,  # 行覆盖率
            "method_nums": int(covered_methods) + int(missed_methods),  # 总方法数
            "method_coverage": coverage_method,  # 方法覆盖率
            "class_nums": int(covered_classes) + int(missed_classes),  # 总类数
            "class_coverage": coverage_class,  # 类覆盖率
            "package_nums": len(packages)  # package数量
        }
        result = dict(code=CODE.PASS.ID, message=CODE.PASS.NAME, data=data, prefix="cov_java")
        return result

    def get_url(self, jacoco_result_path):
        # 不读取jacoco_result_path(例如:/opt/Report/jacoco.xml)，写死jacoco_root_path，与各个工程上报一致
        # jacoco_root_path, xml_name = os.path.split(jacoco_result_path)
        jacoco_root_path = "opt/Report/jacoco-ut"
        product = self.project_name.split("_")[0]
        qingstor_path = get_qingstor_path(jacoco_root_path, job_name=self.project_name, build_id=self.buildid, namespace='coverage', product=product)
        coverage_url = f"http://ecarx.stor.ecarx.com.cn/autobuildtestline/{qingstor_path}/index.html"
        return coverage_url

    def get_result(self, jacoco_result_path):
        return self.get_java_coverage(jacoco_result_path)

    def format_to_weixin(self, result_kwargs, url):
        """
            result_kwargs: {'code': -1, 'message': 'FAIL', 
                    'data': {
                            "line_nums": str(int(covered_lines) + int(missed_lines)),  # 总行数
                            "line_coverage": coverage_line,  # 行覆盖率
                            "method_nums": str(int(covered_methods) + int(missed_methods)),  # 总方法数
                            "method_coverage": coverage_method,  # 方法覆盖率
                            "class_nums": str(int(covered_classes) + int(missed_classes)),  # 总类数
                            "class_coverage": coverage_class,  # 类覆盖率
                            "package_nums": len(packages)  # package数量
                        }}
            url: http://ecarx.stor.ecarx.com.cn/autobuildtestline/{qingstor_path}/index.html
        """
        # title = f"#【{self.project_name}】pipeline #{self.buildid} [stage: {self.stage_name}] 统计结果"
        if result_kwargs:
            content = (f"""\n ## [{self.stage_name} Report] [{result_kwargs["message"]}] [报告地址]({url}) """
                    f"""\n > [总行数]: <font color="comment">{result_kwargs["data"]["line_nums"]}</font> """
                    f"""\n > [行覆盖率]: <font color="comment">{int(result_kwargs["data"]["line_coverage"]) * 100}%</font> """
                    f"""\n > [总方法数]: <font color="comment">{result_kwargs["data"]["method_nums"]}</font> """
                    f"""\n > [方法覆盖率]: <font color="comment">{int(result_kwargs["data"]["method_coverage"]) * 100}%</font> """
                    f"""\n > [总类数]: <font color="comment">{result_kwargs["data"]["class_nums"]}</font> """
                    f"""\n > [类覆盖率]: <font color="comment">{int(result_kwargs["data"]["class_coverage"])* 100}%</font> """
                    f"""\n > [包总数]: <font color="comment">{result_kwargs["data"]["package_nums"]}</font> """)
        else:
            content = f"""\n ## [{self.stage_name} Report] \n <font color="warning">暂无数据</font>"""
        return content
